package it.xiuxian.tradecenter.fragment

import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdNative.NativeExpressAdListener
import com.bytedance.sdk.openadsdk.TTNativeExpressAd
import com.bytedance.sdk.openadsdk.TTNativeExpressAd.ExpressAdInteractionListener
import com.bytedance.sdk.openadsdk.TTNativeExpressAd.ExpressVideoAdListener
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.base.BaseFragment
import it.xiuxian.lib.utils.TTAdManagerHolder
import it.xiuxian.lib.utils.ToastUtil
import it.xiuxian.lib.utils.UIUtils
import it.xiuxian.tradecenter.R
import it.xiuxian.tradecenter.bean.VideoBean
import it.xiuxian.tradecenter.databinding.TradCenterBinding
import it.xiuxian.tradecenter.presenter.NewTradCenterFragmentPresenter
import java.util.*

@Route(path = ArouterAddress.NEWTRADCENTERFRAGMENT)
class NewTradCenterFragment:BaseFragment<NewTradCenterFragmentPresenter>(){
   lateinit private var rvPage2: RecyclerView
   lateinit private var urlList: ArrayList<String>
    private var videoAdapter: ListVideoAdapter? = null
    private var snapHelper: PagerSnapHelper? = null
    private var layoutManager: LinearLayoutManager? = null
    private var mTTAdNative: TTAdNative? = null
    private var currentPosition = 0
    lateinit var binding:TradCenterBinding
    override val layoutId: Int
        get() = R.layout.trad_center
    override val presenter: NewTradCenterFragmentPresenter
        get() = NewTradCenterFragmentPresenter()

    override fun isEmpty(textView: TextView?): Boolean {
        return false
    }

    override fun initView() {
        urlList = ArrayList()
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")
        urlList.add("https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")
       binding =  getViewDataBinding<TradCenterBinding>()
        rvPage2 = binding.rvPage2
        snapHelper = PagerSnapHelper()
        snapHelper!!.attachToRecyclerView(rvPage2)
        videoAdapter = ListVideoAdapter(urlList)
        layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
        //        layoutManager = new GridLayoutManager(Page2Activity.this, 3);
        rvPage2.layoutManager = layoutManager
        rvPage2.adapter = videoAdapter
        mTTAdNative = TTAdManagerHolder.get().createAdNative(requireActivity())
        //在合适的时机申请权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题
        //在合适的时机申请权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题
        TTAdManagerHolder.get().requestPermissionIfNecessary(requireActivity())
       // mPresenter!!.getList()
       // binding.rvPage2
    }
    fun getList(data: VideoBean) {
   // Log.e("videobean",data.toString())
    }

    override fun initEvent() {
        //super.initEvent()
        rvPage2.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {}
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        val view = snapHelper!!.findSnapView(layoutManager)

                        //当前固定后的item position
                        val position = recyclerView.getChildAdapterPosition(view!!)
                        if (currentPosition != position) {
                            //如果当前position 和 上一次固定后的position 相同, 说明是同一个, 只不过滑动了一点点, 然后又释放了
                            MyVideoPlayer.releaseAllVideos()
                            val viewHolder = recyclerView.getChildViewHolder(view)
                            if (viewHolder != null && viewHolder is VideoViewHolder) {
                                viewHolder.mp_video.startVideo()
                                if (position < 2) {
                                    urlList.add(loadNative())
                                }
                            }
                        }
                        currentPosition = position
                    }
                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                    }
                    RecyclerView.SCROLL_STATE_SETTLING -> {
                    }
                }
            }
        })
    }

    private fun loadNative(): String {
        //step3:创建广告请求参数AdSlot,具体参数含义参考文档

        //step3:创建广告请求参数AdSlot,具体参数含义参考文档
        val expressViewWidth: Float = UIUtils.getScreenWidthDp(requireActivity())
        val expressViewHeight: Float = UIUtils.getHeight(requireActivity())

        val adSlot = AdSlot.Builder()
                .setCodeId("947717409")
                .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight) //期望模板广告view的size,单位dp
                .setAdCount(1) //请求广告数量为1到3条
                .build()
        //step4:请求广告,对请求回调的广告作渲染处理
        //step4:请求广告,对请求回调的广告作渲染处理
        mTTAdNative!!.loadExpressDrawFeedAd(adSlot, object : NativeExpressAdListener {
            override fun onError(code: Int, message: String) {
             /*   Log.d(com.union_test.toutiao.activity.DrawNativeExpressVideoActivity.TAG, message)
                showToast(message)*/
            }

            override fun onNativeExpressAdLoad(ads: List<TTNativeExpressAd>) {
                if (ads.isNullOrEmpty()) {
                    ToastUtil.showShort(" ad is null!")
                  //  TToast.show(, " ad is null!")
                    return
                }

                /*if (ads == null || ads.isEmpty()) {
                    TToast.show(this@DrawNativeExpressVideoActivity, " ad is null!")
                    return
                }
                for (i in 0..4) {
                    val random = (Math.random() * 100).toInt()
                    val index: Int = random % videos.size
                    datas.add(com.union_test.toutiao.activity.DrawNativeExpressVideoActivity.Item(com.union_test.toutiao.activity.DrawNativeExpressVideoActivity.TYPE_COMMON_ITEM, null, videos.get(index), imgs.get(index)))
                }*/
                for (ad in ads) {
                  /*  binding.nativeAdContentImageArea.removeAllViews()
                    binding.nativeAdContentImageArea.addView(ad.expressAdView)*/
                    //点击监听器必须在getAdView之前调
                    ad.setVideoAdListener(object : ExpressVideoAdListener{
                        override fun onVideoLoad() {}
                        override fun onVideoError(errorCode: Int, extraCode: Int) {}
                        override fun onVideoAdStartPlay() {}
                        override fun onVideoAdPaused() {}
                        override fun onVideoAdContinuePlay() {}
                        override fun onProgressUpdate(current: Long, duration: Long) {}
                        override fun onVideoAdComplete() {}
                        override fun onClickRetry() {
                           // TToast.show(re, " onClickRetry !")
                            Log.d("drawss", "onClickRetry!")
                        }
                    })
                    ad.setCanInterruptVideoPlay(true)
                    ad.setExpressInteractionListener(object : ExpressAdInteractionListener{
                        override fun onAdClicked(view: View, type: Int) {}
                        override fun onAdShow(view: View, type: Int) {}
                        override fun onRenderFail(view: View, msg: String, code: Int) {}
                        override fun onRenderSuccess(view: View, width: Float, height: Float){
                            binding.nativeAdContentImageArea.removeAllViews()
                            binding.nativeAdContentImageArea.addView(ad.expressAdView)
                          /*  TToast.show(this@DrawNativeExpressVideoActivity, "渲染成功")
                            val random = (Math.random() * 100).toInt()
                            var index: Int = random % videos.size
                            if (index == 0) {
                                index++
                            }
                            datas.add(index, com.union_test.toutiao.activity.DrawNativeExpressVideoActivity.Item(com.union_test.toutiao.activity.DrawNativeExpressVideoActivity.TYPE_AD_ITEM, ad, -1, -1))
                            mAdapter.notifyDataSetChanged()*/
                        }
                    })
                    ad.render()
                }
            }
        })
        return ""
    }

    //创建适配器
    inner class ListVideoAdapter(list: List<String?>?) : BaseRecAdapter<String?, VideoViewHolder?>(list) {


        override fun onCreateHolder(): VideoViewHolder {
            return VideoViewHolder(getViewByRes(R.layout.item_page2))
        }

        override fun onHolder(holder: VideoViewHolder?, bean: String?, position: Int){
            val layoutParams: ViewGroup.LayoutParams = holder!!.itemView.getLayoutParams()
            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
            holder.mp_video.setUp(bean, "第" + position + "个视频", MyVideoPlayer.STATE_NORMAL)
            if (position == 0) {
                holder.mp_video.startVideo()
            }
            Glide.with(context).load(bean).into(holder.mp_video.thumbImageView)
            holder.tv_title.setText("第" + position + "个视频")
        }
    }
    class VideoViewHolder(var rootView: View) : BaseRecViewHolder(rootView){
        var mp_video: MyVideoPlayer
        var tv_title: TextView

        init {
            mp_video = rootView.findViewById(R.id.mp_video)
            tv_title = rootView.findViewById(R.id.tv_title)
        }
    }
}